package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.RelSightRoute;
import com.ruoyi.system.domain.TourGroup;
import com.ruoyi.system.domain.TourRoute;
import com.ruoyi.system.domain.TourSight;
import com.ruoyi.system.mapper.TourRouteMapper;
import com.ruoyi.system.service.ITourRouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TourRouteService implements ITourRouteService {

    @Autowired
    private TourRouteMapper routeMapper;

    @Override
    public TourGroup selectGroupRoutes(int groupId) {
        return routeMapper.selectGroupRoutes(groupId);
    }

    @Override
    public List<TourRoute> selectRoutes() {
        return routeMapper.selectRoutes();
    }

    @Override
    public List<TourRoute> selectRoutes(int cityId) {
        return routeMapper.selectRoutesByCity(cityId);
    }


    @Override
    public int addRoute(TourRoute route) {
        int row = routeMapper.insertRoute(route);
        // 获取插入的id
        int routeId = route.getId();
        List<TourSight> sights = route.getSights();
        List<RelSightRoute> list = getRelList(routeId, sights);
        // 插入此路线与景点的对应关系
        routeMapper.insertRelSightRoute(list);
        return row;
    }

    @Override
    public int updateRoute(TourRoute route) {
        int row = routeMapper.updateRoute(route);
        int routeId = route.getId();
        List<TourSight> sights = route.getSights();
        List<RelSightRoute> list = getRelList(routeId, sights);
        // 更新对应关系
        routeMapper.delRelSightRouteById(routeId);
        routeMapper.insertRelSightRoute(list);
        return row;
    }

    @Override
    public int delRoute(int routeId) {
        int row = routeMapper.delRoute(routeId);
        routeMapper.delRelSightRouteById(routeId);
        return row;
    }

    private List<RelSightRoute> getRelList(int routeId, List<TourSight> sights) {
        int size = sights.size();
        List<RelSightRoute> list = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            list.add(new RelSightRoute(routeId, sights.get(i).getId(), i + 1));
        }
        return list;
    }
}
